<template>
	<view>
		<uni-list :border="true">
			<uni-swipe-action-item
				:right-options="options"
				@click="(e) => onClick(e, index)"
				@change="swipeChange($event, 0)"
				v-for="(item, index) in list"
				:key="index + JSON.stringify(item) + new Date().getTime()"
			>
				<uni-list-item
					@click="() => selectCategory(item)"
			  :title="item.planName + (item.confirmDate ? item.confirmDate : '')"
					clickable
					:note="item.remark"
					time=""
				></uni-list-item>
			</uni-swipe-action-item>
		</uni-list>
		<uni-popup ref="inputDialog" type="dialog">
			<view class="form-container">
				<uni-forms
					:modelValue="formData"
					:rules="rules"
					ref="form"
					label-position="top"
				>
					<!-- <uni-forms-item label="空间名" required name="name">
						<uni-easyinput
							type="text"
							v-model="formData.name"
							placeholder="请输入空间名"
						/>
					</uni-forms-item>
					<uni-forms-item label="空间图" name="image">
						<uni-file-picker
							limit="1"
							@select="select"
							:auto-upload="false"
							return-type="object"
							v-model="formData.image"
						></uni-file-picker>
					</uni-forms-item>
					<uni-forms-item label="备注" name="remark">
						<uni-easyinput
							type="textarea"
							v-model="formData.remark"
							placeholder="请输入备注"
						/>
					</uni-forms-item> -->
				</uni-forms>
				<button class="button" type="primary" @click="submit">保存</button>
			</view>
		</uni-popup>
	</view>
</template>
<script>
import { handleTree } from '@/utils/utils.js'
import { upload,download } from '@/api/plan'
export default {
	data() {
		return {
			formData: {
				id: '',
				name: '',
				image: [],
				remark: ''
			},
			list: [],
			options: [
				{
					text: '复制',
					style: {
						backgroundColor: '#007aff'
					}
				},
				{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}
			],
			rules: {
				name: {
					rules: [
						{
							required: true,
							errorMessage: '请输入产品名'
						}
					]
				}
			}
		}
	},
	onNavigationBarButtonTap: function (e) {
		console.log(e)
		// e的返回格式为json对象：{"text":"测试","index":0}
		switch (e.index) {
			case 0:
				uni.navigateTo({ url: '/pages/my/planAddEdit' })
				break
			case 1:
			var that = this;
			download().then(res=>{
							   if(res.success){
								   const url = res.data;
								   console.log(url)
								   uni.downloadFile({
										url: url, //仅为示例，并非真实的资源
										success: (res) => {
											console.log('下载成功', res)
											const url = plus.io.convertLocalFileSystemURL(res.tempFilePath)
											plus.io.resolveLocalFileSystemURL(
												url,
												function (entry) {
													entry.file(function (file) {
														var reader = new plus.io.FileReader()
														reader.onloadend = function (e) {
															// 这里可以拿到文件内容
															console.log('文件内容：', JSON.parse(e.target.result))
															uni.setStorageSync(
																'plan_list_key',
																e.target.result
															)
															uni.showToast({
																title: '导入成功',
																icon: 'success',
																duration: 2000
															})
															that.getData()
														}
														reader.readAsText(file, 'utf-8') // 也可以用 readAsDataURL、readAsBinaryString 等
													})
												},
												function (e) {
													console.log('resolveLocalFileSystemURL 失败', e)
												}
											)
										}
								   	})
							   }
			})
					
				
				break

			case 2:
				const dataToSav1e = uni.getStorageSync('plan_list_key')
				this.upload(dataToSav1e)
				break
		}
	},
	computed: {
		treeList() {
			const tree = handleTree(this.list)
			console.log(tree)
			return tree
		}
	},
	onLoad() {
		// this.getData()
	},
	onShow() {
		this.getData()
	},
	methods: {
		upload(data){
			upload(data).then(res=>{
				if(res.success){
					uni.showToast({
					  title: '上传成功',
					  icon: 'none',
					  duration: 2000
					})
				}
			})
		},
		getData() {
			uni.getStorage({
				key: 'plan_list_key',
				success: (res) => {
					console.log('获取数据成功', res)
					this.list = JSON.parse(res.data)
					console.log("json",this.list)
				},
				fail: (err) => {
					console.log('获取数据失败', err)
				}
			})
		},
		selectCategory(item) {
			console.log(item)
			uni.navigateTo({
				url: '/pages/my/planAddEdit?id=' + item.id
			})
		},
		swipeChange(e, index) {
			console.log('当前状态：' + e + '，下标：' + index)
		},
		onClick(e, idx) {
			console.log(
				'点击了' +
					(e.position === 'left' ? '左侧' : '右侧') +
					e.content.text +
					'按钮'
			)
			if (e.content.text == '删除') {
				uni.showModal({
					title: '提示',
					content: '确认删除吗？',
					success: (res) => {
						if (res.confirm) {
							let arr = this.list
							arr.splice(idx, 1)
							uni.setStorageSync('plan_list_key', JSON.stringify(arr))
							this.getData()
						}
					}
				})
			} else if (e.content.text == '复制') {
				let arr = this.list
				let item = arr[idx]
				console.log(item)
				arr.push({
					...item,
					id: new Date().getTime().toString(),
					planName: item.planName + '_副本'
				})
				uni.setStorageSync('plan_list_key', JSON.stringify(arr))
				this.getData()
			}
		},
		submit() {
			uni.showLoading()
			this.$refs.form
				.validate()
				.then((res) => {
					uni.hideLoading()
					console.log('表单数据信息：', res, this.formData)
					let data = {
						id: this.formData.id || new Date().getTime().toString(),
						name: this.formData.name,
						image:
							this.formData.image && this.formData.image.length
								? this.formData.image[0].url
								: '',
						remark: this.formData.remark
					}

					const value = uni.getStorageSync('plan_list_key')
					if (value) {
						let arr = JSON.parse(value)
						if (this.formData.id) {
							arr.map((item, index) => {
								if (item.id == this.formData.id) {
									arr.splice(index, 1)
								}
							})
						}
						arr.push(data)
						uni.setStorageSync('plan_list_key', JSON.stringify(arr))
						this.$refs.inputDialog.close()
					} else {
						let arr = []
						arr.push(data)
						uni.setStorageSync('plan_list_key', JSON.stringify(arr))
						this.$refs.inputDialog.close()
					}

					this.getData()
				})
				.catch((err) => {
					uni.hideLoading()
					console.log('表单错误信息：', err)
				})
		},
		select(res) {
			console.log('select', res)
			if (res.tempFiles) {
				let imageInfo = res.tempFiles[0]
				uni.saveFile({
					tempFilePath: imageInfo.image.location,
					success: (res) => {
						console.log('保存文件成功', res)
						const url = plus.io.convertLocalFileSystemURL(res.savedFilePath)
						this.formData.image = [
							{
								url: 'file://' + url,
								image: 'file://' + url,
								location: 'file://' + url,
								name: 'file://' + url
							}
						]
						console.log('保存文件成功', url)
					},
					fail: (err) => {
						console.log('保存文件失败', err)
					}
				})
			}
		}
	},

	onUnload() {}
}
</script>
<style scoped lang="scss">
.form-container {
	width: 90vw;
	background-color: white;
	border-radius: 20rpx;
	padding: 30rpx;
}
</style>
